<template>
  <el-card>
    <div slot="header">
      <h3>{{ getPageTitle() }}</h3>
    </div>
    <div class="page_body">
      <el-form
        ref="formData"
        label-width="120px"
        :model="formData"
        class="alias_manage_body"
      >
        <!-- 商品关键词 -->
        <el-form-item
          prop="keyword"
          label="商品关键词："
          :rules="{ required: true, message: '商品关键词不能为空', trigger: 'change' }"
        >
          <el-select
            v-model="formData.keyword"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            style="width: 100%;"
            :remote-method="getKeywordsByRemoteFuzzy"
            :loading="keywordSelect.loading"
            @change="handleSelectKeyword"
          >
            <el-option
              v-for="item in keywordSelect.options"
              :key="item.keywordUuid"
              :label="item.keyword"
              :value="item.keywordUuid">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 系统推荐别名 -->
        <el-form-item label="系统推荐别名：">
          <span>{{ formData.recommendAliasNames }}</span>
        </el-form-item>
        <!-- 别名 -->
        <div class="alias_wrap">
          <el-form-item
            v-for="(item, index) in formData.aliasNames"
            :key="index"
            :prop="`aliasNames.${index}.aliasName`"
            :label="`别名${index === 0 ? '' : index + 1}：`"
            :rules="{ required: true, message: '别名不能为空', trigger: 'blur' }"
          >
            <el-row>
              <el-col :span="18">
                <el-input
                  v-model.trim="item.aliasName"
                  placeholder="请输入别名"
                  class="margin_right"
                ></el-input>
              </el-col>
              <el-col :span="6">
                <el-button
                  icon="el-icon-minus"
                  circle
                  @click="() => { deleteAlias(index, item) }"
                  :disabled="isOnlyOne()"
                ></el-button>
                <el-button
                  v-if="index === 0"
                  icon="el-icon-plus"
                  circle
                  @click="addAlias"
                  :disabled="isEqualToMaxAmount()"
                ></el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </div>
        <el-form-item label="备注：">
          <el-input
            v-model.trim="formData.comments"
            placeholder="请输入介绍内容"
            type="textarea"
            resize="none"
            show-word-limit
            :autosize="{ minRows: 2, maxRows: 4 }"
            :maxlength="100"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-button
              type="primary"
              :loading="btnLoading.submit"
              @click="handleSubmit"
            >提交</el-button>
            <el-button @click="handleGoBack">返回</el-button>
          </el-row>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>
<script>
import { requestToData, requestToStatus } from '@/api/commonHttp';
import { getArraysByMaps } from '@/utils/getUtils';
export default {
  props: {
    maxAmount: { // 最大别名数量
      type: Number,
      default: 100
    }
  },
  data () {
    return {
      formData: {
        keyword: '', // 关键词
        keywordUuid: '', // 关键词uuid
        aliasNames: [{ aliasName: '', editStatus: '1' }], // 别名集合
        recommendAliasNames: '', // 推荐别名
        comments: '', // 备注
      },
      alreadyExistAlias: new Map(), // 已经存在的别名集合
      keywordSelect: { // 关键词下拉选择
        loading: false, // 加载loading
        options: [], // 下拉options
      },
      btnLoading: { // 按钮loading
        submit: false
      }
    }
  },
  mounted () {
    this.loadInitDataInMounted();
  },
  methods: {
    // 是编辑页面
    isEditPage () {
      return this.$route.query.type === 'edit';
    },
    // 是重新提交页面
    isResubmitPage () {
      return this.$route.query.type === 'resubmit';
    },
    // 是新增页面
    isAddPage () {
      return !this.isEditPage() && !this.isResubmitPage();
    },
    // 别名数量等于最大限制数量
    isEqualToMaxAmount () {
      return this.formData.aliasNames.length >= this.maxAmount;
    },
    isOnlyOne () {
      return this.formData.aliasNames.length === 1;
    },
    // 当前集合为空
    isEmptyForCurrentList (list = this.formData.aliasNames) {
      if (!list) { return true; }
      return list.length === 0;
    },
    // 在mounted时期加载初始数据
    loadInitDataInMounted () {
      if (this.isEditPage()) {
        this.getFormDataDetailsByEdit(this.$route.query?.keywordUuid);
      }
      if (this.isResubmitPage()) {
        this.getFormDataDetailsByResubmit(this.$route.query?.auditKeywordUuid);
      }
    },
    // 设置formData
    setFormData (data) {
      if (!data) { return false; }
      this.formData = { ...data };
      if (this.isEmptyForCurrentList(data.aliasNames)) {
        this.formData.aliasNames = [{ aliasName: '', editStatus: '1' }];
      }
      data.aliasNames.forEach(item => {
        this.updateAlreadyExistAlias(item);
      });
    },
    // 更新alreadyExistAlias
    updateAlreadyExistAlias (item, aliasKey = 'aliasName') {
      this.alreadyExistAlias.set(item[aliasKey], item);
    },
    // 新增别名
    addAlias () {
      this.formData.aliasNames.push({ aliasName: '', editStatus: '1' });
    },
    // 删除别名
    deleteAlias (index, item) {
      this.formData.aliasNames.splice(index, 1);
      if (item.aliasNameUuid) { // 新增别名不会有aliasNameUuid，所以不需要更新alreadyExistAlias
        this.updateAlreadyExistAlias({ ...item, editStatus: '3' });
      }
    },
    // 获取页面标题
    getPageTitle () {
      if (this.isAddPage()) { return '新增' }
      if (this.isEditPage()) { return '编辑' }
      if (this.isResubmitPage()) { return '重新提交' }
    },
    // 远程模糊请求关键词下拉集合
    async getKeywordsByRemoteFuzzy (val) {
      const retData = await requestToData({
        url: `/sysback/product/keyword/getDropDownList?keyword=${val}`,
        type: 'get'
      }, () => { this.keywordSelect.loading = true; },
      () => { this.keywordSelect.loading = false; });
      if (retData) { this.keywordSelect.options = retData; }
    },
    // 获取表单详情（重新提交）
    async getFormDataDetailsByResubmit (auditKeywordUuid) {
      this.getDetailsByUuid(
        '/sysback/product/keyword/audit/getAuditKeywordAliasDetail',
        `auditKeywordUuid=${auditKeywordUuid}`
      );
    },
    // 获取表单详情（编辑）
    getFormDataDetailsByEdit (keywordUuid) {
      if (!keywordUuid) { return false; }
      this.getDetailsByKeywordUuid(keywordUuid);
    },
    // 根据关键词uuid获取表单详情
    getDetailsByKeywordUuid (val) {
      this.getDetailsByUuid(
        '/sysback/product/keyword/getKeywordAliasDetail',
        `keywordUuid=${val}`
      );
    },
    // 根据uuid获取表单详情
    async getDetailsByUuid (url, params) {
      const retData = await requestToData({
        url: `${url}?${params}`,
        type: 'get',
        target: '.page_body'
      });
      if (retData) {
        this.setFormData(retData);
      }
    },
    // 获取提交参数
    getParamsBySubmit () {
      const { aliasNames } = this.formData;
      const alreadyExistAlias = getArraysByMaps(this.alreadyExistAlias);
      const result = aliasNames.map(item => {
        if (alreadyExistAlias.findIndex(
          val => val.aliasNameUuid === item.aliasNameUuid
        ) === -1) {
          return item;
        }
      }).filter(item => item);
      return {
        ...this.formData,
        aliasNames: [...alreadyExistAlias, ...result]
      }
    },
    // 提交-编辑
    submitByEdit () {
      this.submitFormData('/sysback/product/keyword/audit/save');
    },
    // 提交-重新提交
    submitByResubmit () {
      this.submitFormData('/sysback/product/keyword/audit/reSubmit');
    },
    // 提交表单
    async submitFormData (url) {
      const retStatus = await requestToStatus({
        url,
        type: 'post',
        data: this.getParamsBySubmit()
      }, () => { this.btnLoading.submit = true },
      () => { this.btnLoading.submit = false });
      if (retStatus) {
        this.$message.success('提交成功');
        this.handleGoBack();
      }
    },
    // 提交
    handleSubmit () {
      if (this.isResubmitPage()) { // 重新提交
        this.submitByResubmit();
      } else { // 新增；编辑
        this.submitByEdit();
      }
    },
    // 返回
    handleGoBack () {
      const nameByType = {
        'add': 'aliasManageList',
        'edit': 'aliasManageList',
        'resubmit': 'aliasAuditNoPassList'
      }
      const { type } = this.$route.query;
      this.$router.push({ name: nameByType[type] });
    },
    // 选择关键词
    handleSelectKeyword (val) {
      this.getDetailsByKeywordUuid(val)
    },
  }
}
</script>
<style lang="less" scoped>
.alias_wrap {
  max-height: 300px;
  overflow: hidden;
  overflow-y: auto;
  padding-right: 20px;
}
.alias_manage_body {
  margin: 0 20%;
}
.margin_right {
  margin-right: 20px;
}
</style>
